package com.rongke.web.ud;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;


/**
 * 异步通知结果接收接口
 *
 * @author geosmart
 * @date 2017-01-06
 */
public class NotifyResultProcessor {
    /**
     * TODO 获取商户开户的pub_key
     */
   public static final String PUB_KEY = "e91289d5-db06-49c5-b04c-b1d9833dd9fa";
    /**
     * TODO 获取商户开户的security_key
     */
    public static final String SECURITY_KEY = "870c7bf6-4961-4b5b-8146-a51ceb05dfa1";

    public static final String CHARSET_UTF_8 = "UTF-8";
    public static final boolean IS_DEBUG = true;

    /**
     * 生成MD5签名
     *
     * @param pub_key          商户公钥
     * @param partner_order_id 商户订单号
     * @param sign_time        签名时间
     * @param security_key     商户私钥
     */
    public static String getMD5Sign(String pub_key, String partner_order_id, String sign_time, String security_key) throws UnsupportedEncodingException {
        String signStr = String.format("pub_key=%s|partner_order_id=%s|sign_time=%s|security_key=%s", pub_key, partner_order_id, sign_time, security_key);
        System.out.println("signField：" + signStr + SECURITY_KEY);
        return MD5Utils.MD5Encrpytion(signStr.getBytes("UTF-8"));
    }



    /**
     * 获取请求json对象
     */
    public static JSONObject getRequestJson(HttpServletRequest request) throws IOException {
        InputStream in = request.getInputStream();
        byte[] b = new byte[10240];
        int len;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        while ((len = in.read(b)) > 0) {
            baos.write(b, 0, len);
        }
        String bodyText = new String(baos.toByteArray(), CHARSET_UTF_8);
        JSONObject json = (JSONObject) JSONObject.parse(bodyText);
        if (IS_DEBUG) {
            System.out.println("received notify message:");
            System.out.println(JSON.toJSONString(json, true));
        }
        return json;
    }
}
